/* C.ProfileC: Execution profiler (by count)
 *
 * Version 1.00, 04-06-1990
 *
 * Copyright (C) Ferdinand Oeinck 1990
 *
 * Modified, Paul Moore 02/06/91.
 *   To conform to the conventions of my "Utils" library.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "Profile.h"

extern void _mapstore (void);
extern void _fmapstore (const char *);

static char *_profile_filename;
static void _profile_exithandler(void);

void profile_init_count (const char *filename)
{
	if (filename == NULL || *filename == '\0')
		_profile_filename = NULL;
	else
	{
		if ((_profile_filename = malloc(strlen(filename) + 1)) == NULL)
		{
			printf("Warning: Execution count profiling not possible.\n");
			printf("         Malloc failed.\n");
			return;
		}

		strcpy(_profile_filename, filename);
	}

	atexit(_profile_exithandler);
}

static void _profile_exithandler (void)
{
	FILE *fp;

	if (_profile_filename == NULL)
	{
		_mapstore();
	}
	else if ((fp = fopen(_profile_filename, "w")) == NULL)
	{
		fprintf(stderr,"Can't write profile data to %s - using stderr\n",_profile_filename);
		_mapstore();
	}
	else
	{
		fclose(fp);
		_fmapstore(_profile_filename);
	}

	free(_profile_filename);
}
